import React, { FC, useEffect } from 'react';
import { ModalForm } from '@ant-design/pro-form';
import { handleAdd } from '@/utils/actions';
import { ActionType } from '@ant-design/pro-table';

type MegaCreateFormProps = {
  title: string,
  modalVisible: boolean,
  handleModalVisible: React.Dispatch<React.SetStateAction<boolean>>,
  children: React.ReactNode,
  actionRef: React.MutableRefObject<ActionType | undefined>,
  addEntityAction: any,
  transform?: (value: any) => any;
}

export default (props: MegaCreateFormProps) => {
  const { title, modalVisible, handleModalVisible, actionRef, children, addEntityAction, transform } = props;
  return (
    <ModalForm
      title={title}
      visible={modalVisible}
      onVisibleChange={handleModalVisible}
      modalProps={{
        destroyOnClose: true,
      }}
      onFinish={async (value) => {
        const newValue = transform ? transform(value) : value;
        const success = await handleAdd(newValue, addEntityAction);
        if (success) {
          handleModalVisible(false);
          if (actionRef.current) {
            await actionRef.current.reload();
          }
        }
      }}
    >
      {children}
    </ModalForm>
  );
}